articles

Home / DeveloperSection / Articles / how to use data validation in mvc core

how to use data validation in mvc core

how to use data validation in mvc core

Anonymous User 2359 25-May-2019
Today, we will learn how to use data annotation and validate the data before saving in your database. So we need to first understand what is data annotation? 
What is Data Annotation?
"Data Annotation provides attribute classes that are used to define metadata for ASP.NET MVC and ASP.NET data controls."
Let's see it now. In this example, we are going to use data annotation to validate model data before submitting the form.
So, you need to create your database first in SQL Server.
To create a new database first open “Microsoft SQL Server Management Studio” and right-click on Database node and choose New Database.
Open New Query window and execute the following code in the query window:
create database TechMindCore
Create a table in Database like below:
 CREATE TABLE Movie

(
ID bigint primary key identity(1,1),
Title nvarchar(100),
ReleaseDate DateTime,
Genre nvarchar(100),
Price Decimal(10,2)
)
Now Open Visual Studio 2017 and let’s create a new ASP.NET Core Web Application project. To do this, Select File > New > Project. In the New Project dialog select Visual C# > Web > ASP.NET Core Web Application just like in the figure below:
how to use data validation in mvc core
Figure 1: ASP.NET Core Web Application Project Template
Name your project to whatever you like, but for this exercise, we will name it as “AspDotNetCoreMvc” to confirm with the topic. Click OK and then select “Web Application (Model-View-Controller)” within ASP.NET Core templates as shown in the following figure below:
how to use data validation in mvc core
Figure 2: ASP.NET Core Web Application Template
Now click on Change Authentication box.
Select the individual User Accounts options and then click the OK button to let Visual Studio generate the required files needed for us to run the application. The figure below shows the default generated files:
how to use data validation in mvc core
Figure 3: The Models ,Views and Controller
Now, open the appsettings.json file and provide the database name, database server name, and related credentials to establish the connection with the database.
{

  "ConnectionStrings": {
    "DefaultConnection": "Password=sa@123;Persist Security Info=True;User ID=sa;Initial Catalog=TechMindCore;Data Source=(local)"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}
Integrating Entity Framework Core
Now, in order to import existing database context object using entity framework to my core web application, I need to install the following library packages via "Tools->NuGet Package Manager->Manage NuGet Packages for Solution".
Now, right-click on the root of your application and then select Manage NuGet Packages. Select the Browse tab and in the search bar, type in “Microsoft.EntityFrameworkCore.SqlServer”. It should result to something like this:
how to use data validation in mvc core
Figure 4: Manage NuGet Package
 we are going to use Database-First development approach to work with existing database, we need to install the additional packages below as well:
        • Microsoft.EntityFrameworkCore.Tools (v2.0.1)
        • Microsoft.EntityFrameworkCore.SqlServer.Design (v1.1.4)
Using Nuget Package Manager GUI
Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution, then type in "Microsoft.EntityFrameworkCore.Tools”. Click install just like in the figure below:
how to use data validation in mvc core
Figure 5: Adding Microsoft.EntityFrameworkCore.Tools package
When it’s done installing all the required packages, you should be able to see them added to your project dependencies as shown in the figure below:
how to use data validation in mvc core
Figure 6: Entity Framework Core Packages installed
Creating Entity Models from Existing Database Using Package Manager Console
Now Click "Tools->NuGet Package Manager->Package Manager Console" as shown below:
how to use data validation in mvc core
Figure 7: Console Manager Package
Type the following command inside the console as shown below.
Scaffold-DbContext "Server=(local);Database=TechMindCore;Trusted_Connection=True;user id=sa;password=sa@123;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DataBase
how to use data validation in mvc core
Figure 8: Console Manager Package window
The Server attribute above is the SQL server instance name. You can find it in SQL Management Studio by right clicking on your database. For this example, the server name is “(local)”.
The Database attribute is your database name. In this case, the database name is “TechMindCore”.
The –OutputDir attribute allows you to specify the location of the files generated. In this case, we’ve set it to Models/DataBase.
The command above will generate models from existing database within Models/DB folder. Here’s the screenshot below:
how to use data validation in mvc core
Figure 9: database context object Output.
Now see above highlighted File “TechMindCoreContext.cs” DbContext Generated successfully.
Now create a MovieMetadata model class to define data annotation validation attribute.
 using Microsoft.AspNetCore.Mvc;

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models.DataBase
{
    [ModelMetadataType(typeof(MovieMetadata))]
    public partial class Movie
    {
    }
    public class MovieMetadata
    {
        public long Id { get; set; }
        [Required(ErrorMessage = "Title is required")]
        public string Title { get; set; }

        [Required(ErrorMessage = "Date is required")]
        public DateTime ReleaseDate { get; set; }

        [Required(ErrorMessage = "Genre must be specified")]
        public string Genre { get; set; }

        [Required(ErrorMessage = "Price is required")]
        [Range(1, 100, ErrorMessage = "Price must be between $1 and $100")]
        public decimal Price { get; set; }
    }
}
Creating View and Controller
The next step is to create UI. In this step, I have created Controller and View. I have “MovieController.cs” file under the Controllers folder and created two Views under the “Views” folder. Following snap is showing the hierarchy of folders and files within our project.
how to use data validation in mvc core
Figure 10: ASP.NET Core controller and view
Following is the code snippet for MovieController.
MovieController.cs
 using System;

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models.DataBase;
namespace WebApplication1.Controllers
{
    public class MovieController : Controller
    {
        TechMindCoreContext db = new TechMindCoreContext();


        public IActionResult Create()
        {
            ViewBag.title = "Create";
            return View();
        }
            [HttpPost]
        public IActionResult Create(Movie model)
        {
            ModelState.Remove("Id");
            if (ModelState.IsValid)
            {
                if (model.Id <= 0)
                {
                    db.Movie.Add(model);
                }
                else
                {
                    var movie = db.Movie.FirstOrDefault(x => x.Id == model.Id);
                    movie.Title = model.Title;
                    movie.Price = model.Price;
                    movie.Genre = model.Genre;
                    movie.ReleaseDate = model.ReleaseDate;
                }
                db.SaveChanges();
                return RedirectToAction("Index", "Movie");
            }
            return View();

        }


    }
}
Create add /edit view
Now, I am defining the "Add/Edit" View. The following is the code snippet for "Create.cshtml".
Create.cshtml

@model WebApplication1.Models.DataBase.Movie

@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";

}

<h2>Create/Edit Movie</h2>
<h4>Movie</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <input asp-for="Id" class="form-control" type="hidden" />
            </div>
            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ReleaseDate" class="control-label"></label>
                <input asp-for="ReleaseDate" class="form-control" />
                <span asp-validation-for="ReleaseDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Genre" class="control-label"></label>
                <input asp-for="Genre" class="form-control" />
                <span asp-validation-for="Genre" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Now build and run the application using CTRL + 5. In the browser, navigate to /movie/create. It should bring up the following page.
 When you click on save button without filling form it will so required error.
how to use data validation in mvc core
Now, in this article, we learn the data annotation validation step by step in ASP.NET Core. I hope, this will help the readers to understand how to complete validation in asp.net mvc core.


Updated 24-Dec-2019
I am a content writter !

Leave Comment

Comments

Liked By